#!/usr/local/bin/python
# Author: Jimmy Saw
# Date: 01/05/2011
# This script checks Blast2table output files (format -8 option)
# for lengths. If there are less then 10 hits, it averages all
# lengths. If there are more than 10 hits, it counts the first
# top 10 hits for length comparison with query length.
# Query name, QueryLength, AvgHitLength, %(query/avg)

import sys

filename = sys.argv[1] + '.blastp.tbl'

f = open(filename, "r")

lines = f.readlines()

def fmt(f):
  st = '{0:.4}'.format(f)
  return st

if len(lines) == 0:
  print sys.argv[1], "\t", "empty"
else:
  hits = len(lines)
  first = lines[0]
  fl = first.split('\t')
  queryLength = fl[6] 
  hitLength = 0
  if len(lines) < 10:
    for line in lines:
      l = line.split('\t')
      hitLength += float(l[10])
    avgHL = hitLength/hits
    perHL = (float(queryLength)/avgHL)*100
    print sys.argv[1], "\t", queryLength, "\t", fmt(avgHL), "\t", fmt(perHL)
  else:
    for line in lines[0:10]:
      l = line.split('\t')
      hitLength += float(l[10])
    avgHL = hitLength/10
    perHL = (float(queryLength)/avgHL)*100
    print sys.argv[1], "\t", queryLength, "\t", fmt(avgHL), "\t", fmt(perHL)

f.close()

